<template>
  <div class="table-page-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="system-user-search">
        <el-form ref="searchFormRef" :model="searchForm" inline>
          <el-form-item label="订单号" prop="order_no">
            <el-input v-model="searchForm.order_no" placeholder="请输入"> </el-input>
          </el-form-item>
          <el-form-item label="联系人" prop="contact_name">
            <el-input v-model="searchForm.contact_name" placeholder="请输入" style="width: 160px">
            </el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="contact_phone">
            <el-input v-model="searchForm.contact_phone" placeholder="请输入" style="width: 160px">
            </el-input>
          </el-form-item>
          <el-form-item label="活动" prop="activity_id">
            <CommonSelect
              v-model="searchForm.activity_id"
              :options="state.activityList"
              label-key="name"
              value-key="id"
              filterable
              remote
              reserve-keyword
              remote-show-suffix
              style="width: 160px"
              :remote-method="searchActivity"
              :loading="state.loading"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <CommonSelect
              v-model="searchForm.status"
              style="width: 120px"
              :options="statusOptions"
              placeholder="请选择"
            >
            </CommonSelect>
          </el-form-item>
          <el-form-item label="推广人手机号" prop="promoter_uid">
            <el-input v-model="searchForm.promoter_mobile" style="width: 200px" placeholder="请输入">
            </el-input>
          </el-form-item>
          <el-form-item label="推广机构名称" prop="org_name">
            <el-input v-model="searchForm.org_name" style="width: 160px" placeholder="请输入">
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="default" type="primary" @click="refresh">
              <el-icon>
                <ele-Search />
              </el-icon>
              查询
            </el-button>
            <el-button size="default" @click="onReset">
              <el-icon>
                <ele-RefreshRight />
              </el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="mb15">
        <el-button type="primary" @click="handleOrderExport">导出订单列表</el-button>
        <el-button type="primary" @click="handleMemberExport">导出报名表</el-button>
      </div>
      <el-table
        :data="tableData.list"
        v-loading="loading"
        element-loading-text="加载中"
        border
        style="width: 100%"
      >
        <el-table-column prop="order_no" label="订单号" width="190" fixed="left"></el-table-column>
        <el-table-column prop="write_off_code" label="核销号" width="150"></el-table-column>
        <el-table-column
          prop="amount"
          label="订单金额"
          width="109"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="报名人数" width="100" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.members.split(',').length }}
          </template>
        </el-table-column>
        <el-table-column
          prop="contact_name"
          label="联系人"
          width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="contact_phone"
          label="联系电话"
          width="120"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="activity_item.activity.name"
          label="活动名称"
          width="160"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="activity_item.name"
          label="项目名称"
          width="160"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column prop="org_name" width="100" label="机构名称">
          <template #default="{ row }">
            {{ row.org_name || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <ActivityOrderStatusComp :status="row.status"></ActivityOrderStatusComp>
          </template>
        </el-table-column>
        <el-table-column
          prop="created_at"
          label="报名时间"
          width="180"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <el-button
              v-if="$can(ButtonPermission.READ_ACTIVITY_ORDER)"
              size="small"
              text
              type="primary"
              @click="handleView(scope.row)"
              >查看</el-button
            >
            <el-button
              v-if="
                scope.row.status === ActivityOrderStatus.UN_WRITE_OFF &&
                $can(ButtonPermission.WRITE_OFF_ACTIVITY_ORDER)
              "
              size="small"
              text
              type="primary"
              @click="handleWriteOff(scope.row)"
              >核销</el-button
            >
            <el-button
              v-if="
                scope.row.status === ActivityOrderStatus.WRITED_OFF &&
                $can(ButtonPermission.WRITE_OFF_ACTIVITY_ORDER)
              "
              size="small"
              text
              type="primary"
              @click="handleRevertWriteOff(scope.row)"
              >撤销核销</el-button
            >
            <el-button
              v-if="
                (scope.row.status === ActivityOrderStatus.UN_WRITE_OFF ||
                  scope.row.status === ActivityOrderStatus.REFUND_FAIL) &&
                $can(ButtonPermission.REFUND_ACTIVITY_ORDER)
              "
              size="small"
              text
              type="primary"
              @click="handleRefund(scope.row)"
              >退款</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <CommonPagination :pagination="pagination" :total="tableData.total"></CommonPagination>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="orderList">
import { ref, reactive } from 'vue';
import { ElLoading, ElMessage, FormInstance } from 'element-plus';
import {
  readAllActivityOrder,
  writeOff,
  revertWriteOff,
  refund,
  exportData, exportActivityMemberData
} from '/@/api/activity-order';
import { readAllActivity } from '/@/api/activity';
import { useTable } from '/@/hooks/use-table';
import CommonPagination from '/@/components/common-pagination/index.vue';
import { ButtonPermission } from '/@/constants';
import ActivityOrderStatusComp from '/@/components/activity-order-status/index.vue';
import CommonSelect from '/@/components/common-select/index.vue';
import { toOptions } from '/@/hooks/use-options';
import { ActivityOrderStatusLabel, ActivityOrderStatus } from '/@/constants/activity-order-status';
import { debounce } from 'lodash';
import { confirm } from '/@/utils/confirm';
import { useRouter } from 'vue-router';
import { download } from '/@/utils/download';

const router = useRouter();
const searchFormRef = ref<FormInstance>();
const searchForm = reactive({
  order_no: undefined,
  contact_name: undefined,
  contact_phone: undefined,
  activity_id: undefined,
  status: undefined,
  activity_item_id: undefined,
  promoter_mobile: undefined,
  org_name: undefined
});

const state = reactive({
  activityList: [],
  loading: false
});

const statusOptions = toOptions(ActivityOrderStatusLabel);

const { tableData, loading, pagination, refresh, resetAndRefresh } = useTable<any>(
  ({ page, pageSize }) =>
    readAllActivityOrder({ page, pageSize, ...searchForm }).then(({ data }) => {
      return {
        total: data?.total,
        list: data?.list
      };
    })
);

const handleWriteOff = (row: any) => {
  confirm(
    async () => {
      await writeOff({ write_off_codes: [row.write_off_code] });
      ElMessage.success('核销成功');
      refresh();
    },
    '是否确认核销',
    '提示'
  );
};

const handleRevertWriteOff = (row: any) => {
  confirm(
    async () => {
      await revertWriteOff({ write_off_codes: [row.write_off_code] });
      ElMessage.success('核销成功');
      refresh();
    },
    '是否确认撤销核销',
    '提示'
  );
};

const handleRefund = (row: any) => {
  confirm(
    async () => {
      await refund(row.id);
      ElMessage.success('核销成功');
      refresh();
    },
    '退款后不可恢复，请确认是否继续退款？',
    '警告'
  );
};

const searchActivity = debounce(
  async (query: string) => {
    const trimQuery = query.trim();
    if (trimQuery) {
      state.loading = true;
      try {
        const { data } = await readAllActivity({ name: trimQuery, page: 1, pageSize: 1000 });
        state.activityList = data.list;
      } catch (err) {
        console.error(err);
      }
      state.loading = false;
    }
  },
  500,
  {
    leading: true
  }
);

const handleView = (row: any) => {
  router.push({
    name: 'activityOrderDetail',
    query: { id: row.id }
  });
};

const onReset = () => {
  searchFormRef.value?.resetFields();
  resetAndRefresh();
};

const handleOrderExport = async () => {
  const loading = ElLoading.service({ fullscreen: true, text: '导出中' });
  try {
    const params: any = { ...searchForm };
    const blob = await exportData(params);
    download(blob, `订单列表-${Date.now()}.xlsx`);
  } catch (err) {
    console.log(err);
  }
  loading.close();
};

const handleMemberExport = async () => {
  const loading = ElLoading.service({ fullscreen: true, text: '导出中' });
  try {
    const params: any = { ...searchForm };
    const blob = await exportActivityMemberData(params);
    download(blob, `报名表-${Date.now()}.xlsx`);
  } catch (err) {
    console.log(err);
  }
  loading.close();
};
</script>
